import * as vscode from 'vscode';
import * as path from 'path';
import { LsykApi } from './api';

// 定义树节点类型
interface LsykTreeNode {
    id: string;
    label: string;
    description?: string;
    iconPath?: string | vscode.Uri;
    command?: vscode.Command;
    children?: LsykTreeNode[];
    isFile?: boolean;
    imageUrl?: string;
}

export class LsykUploadPanel implements vscode.TreeDataProvider<LsykTreeNode> {
    private _onDidChangeTreeData: vscode.EventEmitter<LsykTreeNode | null> = new vscode.EventEmitter<LsykTreeNode | null>();
    readonly onDidChangeTreeData: vscode.Event<LsykTreeNode | null> = this._onDidChangeTreeData.event;

    private context: vscode.ExtensionContext;
    private api: LsykApi;
    private imageCache: LsykTreeNode[] = [];

    constructor(context: vscode.ExtensionContext, api: LsykApi) {
        this.context = context;
        this.api = api;

        // 初始化加载图片列表
        this.loadImages();
    }

    // 刷新树数据
    public refresh(): void {
        this._onDidChangeTreeData.fire(null);
        this.loadImages();
    }

    // 加载图片列表
    private async loadImages(): Promise<void> {
        try {
            const result = await this.api.getImages();
            if (result && result.status) {
                this.imageCache = result.data.data.map(image => ({
                    id: image.key,
                    label: image.origin_name,
                    description: `${(image.size / 1024).toFixed(2)} KB`,
                    iconPath: this.getImageIconPath(),
                    isFile: true,
                    imageUrl: image.links.url,
                    imageData: image, // 存储完整的图片数据用于展示详情
                    command: {
                        command: 'lsyk-upload-vs-plugin.showImageDetails',
                        title: '查看图片详情',
                        arguments: [image]
                    }
                }));
                this.refresh();
            }
        } catch (error) {
            vscode.window.showErrorMessage(`加载图片列表出错: ${error instanceof Error ? error.message : String(error)}`);
        }
    }

    // 获取图片图标路径
    private getImageIconPath(): string {
        return path.join(this.context.extensionPath, 'resources', 'image.svg');
    }

    // 获取根节点
    getChildren(element?: LsykTreeNode): Thenable<LsykTreeNode[]> {
        if (!element) {
            // 根节点包含上传按钮、设置按钮和图片列表
            const rootItems: LsykTreeNode[] = [
                {
                    id: 'upload',
                    label: '上传图片',
                    iconPath: path.join(this.context.extensionPath, 'resources', 'upload.svg'),
                    command: {
                        command: 'lsyk-upload-vs-plugin.uploadImage',
                        title: '上传图片'
                    }
                },
                {
                    id: 'settings',
                    label: '设置',
                    iconPath: path.join(this.context.extensionPath, 'resources', 'settings.svg'),
                    command: {
                        command: 'lsyk-upload-vs-plugin.setApiConfig',
                        title: '设置'
                    }
                },
                {
                    id: 'images',
                    label: '已上传图片',
                    iconPath: this.getImageIconPath(),
                    children: this.imageCache
                }
            ];
            return Promise.resolve(rootItems);
        }

        // 如果是图片节点，没有子节点
        if (element.id === 'images') {
            return Promise.resolve(element.children || []);
        }

        return Promise.resolve([]);
    }

    // 获取树节点信息
    getTreeItem(element: LsykTreeNode): vscode.TreeItem {
        const treeItem = new vscode.TreeItem(element.label);
        treeItem.id = element.id;
        treeItem.description = element.description;
        treeItem.iconPath = element.iconPath;
        treeItem.command = element.command;

        if (element.children && element.children.length > 0) {
            treeItem.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;
        } else if (element.children) {
            treeItem.collapsibleState = vscode.TreeItemCollapsibleState.None;
        }

        // 如果是图片文件，添加右键菜单
        if (element.isFile && element.imageUrl) {
            treeItem.contextValue = 'image';
        }

        return treeItem;
    }
}